package com.wwh.proxy2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @author Albert
 * @date 2024/8/26-21:50
 * @describe
 */
public class CalculatorProxy {
    SmartAnimal sa;

    public CalculatorProxy(SmartAnimal sa) {
        this.sa = sa;
    }

    public SmartAnimal getProxy(){
        //得到类加载器
        ClassLoader classLoader = sa.getClass().getClassLoader();

        //得到代理对象的接口信息
        Class<?>[] interfaces = sa.getClass().getInterfaces();

        //创建调用处理器
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //AOP编程
                try {
                    System.out.print("日志-方法名-" + method.getName() + "-参数" + Arrays.asList(args));//前置通知
                    //for (int i = 0; i < args.length; i++){
                    //    System.out.print(" " + args[i]);
                    //}
                    System.out.println(" ");
                    Object res = method.invoke(sa, args);
                    System.out.println("日志-方法名-" + method.getName() + "-结果resul=" + res);//返回通知
                    return res;
                } catch (Exception e) {
                    System.out.println("日志-方法名-" + method.getName() + "-异常=" + e.getClass().getName());//异常通知
                } finally {
                    System.out.println("日志-方法名-" + method.getName() + "-结束");//最终通知
                }
                return null;
            }
        };
        return (SmartAnimal) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
    }
}
